import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';

import 'package:get/get.dart';

class EmptyPage extends StatefulWidget {
  const EmptyPage({super.key});

  @override
  State<EmptyPage> createState() => _EmptyPageState();
}

class _EmptyPageState extends State<EmptyPage> {
  Map<String, int> keyPressData = {};
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _fetchData();
    _timer = Timer.periodic(const Duration(seconds: 5), (timer) {
      _fetchData();
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Future<void> _fetchData() async {
    try {
      // final response = await http.get(Uri.parse('http://localhost:8080/api/keypress/minutes'));
      var response = await Dio().get(
        'http://localhost:8080/api/keypress/minutes',
      );
      final data = response.data;
      setState(() {
        keyPressData = {'A': 1, 'B': 22, 'C': 33, 'D': 66};
      });
    } catch (e) {
      debugPrint('Error fetching data: $e');
      e.printError();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Container(
          padding: const EdgeInsets.all(20),
          width: double.infinity,
          height: double.infinity,
          child: CustomPaint(
            painter: BarChartPainter(keyPressData),
            child: Container(),
          ),
        ),
      ),
    );
  }
}

class BarChartPainter extends CustomPainter {
  final Map<String, int> data;
  final Paint barPaint;
  final Paint axisPaint;
  final TextPainter textPainter;

  BarChartPainter(this.data)
    : barPaint =
          Paint()
            ..color = Colors.blue
            ..style = PaintingStyle.fill,
      axisPaint =
          Paint()
            ..color = Colors.black
            ..style = PaintingStyle.stroke
            ..strokeWidth = 2.0,
      textPainter = TextPainter(
        textDirection: TextDirection.ltr,
        textAlign: TextAlign.center,
      );

  @override
  void paint(Canvas canvas, Size size) {
    final double padding = 40.0;
    final double chartWidth = size.width - (padding * 2);
    final double chartHeight = size.height - (padding * 2);
    final double bottom = size.height - padding;
    final double left = padding;

    // 绘制坐标轴
    canvas.drawLine(
      Offset(left, bottom),
      Offset(size.width - padding, bottom),
      axisPaint,
    );
    canvas.drawLine(Offset(left, bottom), Offset(left, padding), axisPaint);

    if (data.isEmpty) return;

    final int maxValue = data.values.reduce((a, b) => a > b ? a : b);
    final double barWidth = chartWidth / (data.length * 2);
    final double scale = chartHeight / maxValue;

    var index = 0;
    data.forEach((key, value) {
      // 绘制柱状图
      final double x = left + (index * 2 + 1) * barWidth;
      final double barHeight = value * scale;
      final Rect barRect = Rect.fromLTWH(
        x,
        bottom - barHeight,
        barWidth,
        barHeight,
      );
      canvas.drawRect(barRect, barPaint);

      // 绘制键名标签
      textPainter.text = TextSpan(
        text: key,
        style: const TextStyle(fontSize: 12),
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset(x + (barWidth - textPainter.width) / 2, bottom + 5),
      );

      // 绘制数值标签
      textPainter.text = TextSpan(
        text: value.toString(),
        style: const TextStyle(fontSize: 12),
      );
      textPainter.layout();
      textPainter.paint(
        canvas,
        Offset(x + (barWidth - textPainter.width) / 2, bottom - barHeight - 20),
      );

      index++;
    });
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
